<template>
  <div class="page-posts">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :offset="50"
      @load="onLoad"
    >
      <van-cell
        v-for="post in posts"
        :key="post.id"
        :title="post.title"
        :label="post.content"
        is-link
        :to="`/posts/${post.id}`"
      >
        <template v-slot:icon>
          <img class="page-posts__img" v-lazy="post.photos[0]" alt />
        </template>
      </van-cell>
    </van-list>
  </div>
</template>

<script>
import Axios from "axios";

export default {
  name: "Posts",

  inject: ["home"],

  data() {
    return {
      loading: false,
      finished: false,
      page: 0,
      limit: 10,
      totalPages: 1,
      posts: [],
      scrollTop: 0
    };
  },

  methods: {
    onLoad() {
      if (this.page >= this.totalPages) {
        this.finished = true;
        return;
      }

      this.page++;

      Axios.get("http://localhost:3000/posts", {
        params: {
          _page: this.page,
          _limit: this.limit
        }
      }).then(response => {
        this.posts = [...this.posts, ...response.data];
        this.totalPages = Math.ceil(
          response.headers["x-total-count"] / this.limit
        );
        this.loading = false;
      });
    }
  },

  activated() {
    this.$store.commit("SET_TITLE", "列表");
    this.home.$refs["homeView"].scrollTop = this.scrollTop;
  },

  beforeRouteLeave(to, from, next) {
    this.scrollTop = this.home.$refs["homeView"].scrollTop;
    next();
  }
};
</script>

<style lang="scss">
.page-posts {
  .van-cell {
    align-items: center;
  }
  .van-cell__label {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
    overflow: hidden;
  }
  &__img {
    width: 40px;
    margin-right: 15px;
  }
}
</style> 
